package com.adou.quartz.action;

import com.adou.quartz.task.Task;
import com.adou.quartz.task.TaskGroupAction;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuartzManager {

    private static final String JOB_GROUP_NAME = "group1";

    private static final Logger logger = LoggerFactory.getLogger(QuartzManager.class);

    @Autowired
    private Scheduler scheduler;

    public void addTask(Task task) {
        try {
            // 创建jobDetail实例，绑定Job实现类
            // 指明job的名称，所在组的名称，以及绑定job类
            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(task.getClassname()).newInstance()
                    .getClass());
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(task.getId(), JOB_GROUP_NAME)// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getId(), JOB_GROUP_NAME)// 触发器key
                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronexpresssion())).startNow().build();
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
    }

    /**
     * 所有正在运行的task
     *
     * @return
     * @throws SchedulerException
     */
    public List<Task> getRunningTask() throws SchedulerException {
        List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
        List<Task> taskList = new ArrayList<Task>(executingJobs.size());
        for (JobExecutionContext executingJob : executingJobs) {
            JobDetail jobDetail = executingJob.getJobDetail();
            JobKey jobKey = jobDetail.getKey();
            Trigger trigger = executingJob.getTrigger();
            Task task= new TaskGroupAction().getTaskById(jobKey.getName());
            task.setState(1);
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                String cronExpression = cronTrigger.getCronExpression();
                task.setCronexpresssion(cronExpression);
            }
            taskList.add(task);
        }
        return taskList;
    }

    /**
     * 暂停一个task
     *
     * @param id
     * @throws SchedulerException
     */
    public void pauseTask(String id) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(id, JOB_GROUP_NAME);
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复一个task
     *
     * @param id
     * @throws SchedulerException
     */
    public void resumeTask(String id) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(id, JOB_GROUP_NAME);
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除一个task
     *
     * @param id
     * @throws SchedulerException
     */
    public void deleteTask(String id) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(id, JOB_GROUP_NAME);
        scheduler.deleteJob(jobKey);

    }

    /**
     * 立即执行task
     *
     * @param id
     * @throws SchedulerException
     */
    public void runATaskNow(String id) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(id, JOB_GROUP_NAME);
        scheduler.triggerJob(jobKey);
    }
}